<template>
  <div class="show-main">
    <el-scrollbar style="height:100%">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <el-form :inline="true" :model="searchForm" ref="searchForm">
            <el-form-item prop="name">
              <el-input v-model="searchForm.name" clearable placeholder="请输入角色名称"></el-input>
            </el-form-item>
            <el-form-item prop="status">
              <el-select v-model="searchForm.status" clearable placeholder="请选择状态">
                <el-option label="正常" value="1"></el-option>
                <el-option label="禁用" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click.stop="search(true)">搜索</el-button>
              <el-button type="success" @click.stop="search">刷新</el-button>
              <el-button type="warning" @click.stop="add">添加</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="table" border>
          <el-table-column prop="id" label="ID"></el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <span>
                <el-tooltip :content="scope.row.status == 0 ? '禁用' : '正常'" placement="top" :enterable="false">
                  <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="changeStatus(scope.row)"> </el-switch>
                </el-tooltip>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间">
            <template slot-scope="scope">
              {{ scope.row.create_time | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button type="text" @click="edit(scope.row.id)">角色编辑</el-button>
              <el-button type="text" @click="editMenu(scope.row.id)">菜单编辑</el-button>
              <el-button type="text" @click="del(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="searchForm.page"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="searchForm.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="count"
          >
          </el-pagination>
        </div>
      </el-card>
      <el-dialog title="编辑角色" :visible.sync="editVisible" :before-close="handleClose('editForm')">
        <el-form ref="editForm" :model="editForm" label-width="80px" :rules="rules">
          <el-form-item label="名称" prop="name">
            <el-input v-model="editForm.name"></el-input>
          </el-form-item>
          <el-form-item label="权限" prop="menu_ids">
            <el-tree
              :data="menuList"
              node-key="id"
              ref="editTree"
              highlight-current
              accordion
              :props="defaultProps"
              show-checkbox
              @check-change="handleCheckChangeEdit"
              :default-checked-keys="checkedKeys"
            >
            </el-tree>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('editVisible', 'editForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('editVisible', 'editForm')" size="small">编 辑</el-button>
        </span>
      </el-dialog>
      <el-dialog title="添加角色" :visible.sync="addVisible" :before-close="handleClose('addForm')">
        <el-form ref="addForm" :model="addForm" label-width="80px" :rules="rules">
          <el-form-item label="名称" prop="name">
            <el-input v-model="addForm.name"></el-input>
          </el-form-item>
          <el-form-item label="权限" prop="menu_ids">
            <el-tree
              :data="menuList"
              node-key="id"
              ref="addTree"
              highlight-current
              accordion
              :props="defaultProps"
              show-checkbox
              @check-change="handleCheckChangeAdd"
            >
            </el-tree>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('addVisible', 'addForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('addVisible', 'addForm')" size="small">添 加</el-button>
        </span>
      </el-dialog>
      <el-dialog title="编辑角色菜单" :visible.sync="editMenuVisible" :before-close="handleClose('editMenuForm')">
        <el-form ref="editMenuForm" :model="editMenuForm" label-width="80px" :rules="rules">
          <el-form-item label="菜单" prop="left_menu_ids">
            <el-tree
              :data="menuList"
              node-key="id"
              ref="editMenuTree"
              highlight-current
              accordion
              :props="defaultProps"
              show-checkbox
              @check-change="handleCheckChangeEditMenu"
              :default-checked-keys="checkedKeys"
            >
            </el-tree>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('editMenuVisible', 'editMenuForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('editMenuVisible', 'editMenuForm')" size="small">编 辑</el-button>
        </span>
      </el-dialog>
    </el-scrollbar>
  </div>
</template>
<script>
import { getRoleList, getAdminAuth, getRoleOnly, getRoleMenuOnly, addRole, changeRoleStatus, editRole, editRoleMenu, delRole } from '@/network/api.js'

export default {
  name: 'role',
  data() {
    return {
      searchForm: {
        page: 1,
        limit: 10,
        name: '',
        status: ''
      },
      table: [],
      count: 0,
      detaiForm: {
        id: 0,
        pid: 0,
        name: '',
        icon: '',
        api: '',
        router: '',
        component: '',
        is_show: 0,
        level: 0,
        create_time: 0
      },
      editForm: {
        id: 0,
        name: '',
        menu_ids: []
      },
      // 添加表单
      addForm: {
        name: '',
        menu_ids: []
      },
      editMenuForm: {
        id: 0,
        left_menu_ids: []
      },
      menuList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      checkedKeys: [], // 默认选中
      detailVisible: false, // 详情
      editVisible: false, // 编辑
      editMenuVisible: false, // 编辑
      addVisible: false, // 添加
      rules: {
        name: [{ required: true, message: '权限名称必须', trigger: 'blur' }],
        menu_ids: [{ type: 'array', required: true, message: '请至少选择一个权限', trigger: 'change' }],
        left_menu_ids: [{ type: 'array', required: true, message: '请至少选择一个菜单', trigger: 'change' }]
      }
    }
  },
  created() {
    this.search()
  },
  computed: {},
  methods: {
    // 每页条数变化
    handleSizeChange(val) {
      this.searchForm.limit = val
      this.search()
    },
    // 当前页变化
    handleCurrentChange(val) {
      this.searchForm.page = val
      this.search()
    },
    async search(pageInit = false) {
      try {
        if (pageInit === true) {
          this.searchForm.page = 1
        }
        const rtn = await getRoleList(this.searchForm)
        this.table = rtn.list
        this.count = rtn.count
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 添加
    async add() {
      try {
        const rtn = await getAdminAuth({})
        this.menuList = rtn
        this.addVisible = true
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 添加表单权限选择
    handleCheckChangeAdd(data, checked, indeterminate) {
      this.$set(
        this.addForm,
        'menu_ids',
        [...this.$refs.addTree.getHalfCheckedKeys(), ...this.$refs.addTree.getCheckedKeys()].sort((a, b) => {
          return a - b
        })
      )
    },
    // 添加表单权限选择
    handleCheckChangeEdit(data, checked, indeterminate) {
      this.$set(
        this.editForm,
        'menu_ids',
        [...this.$refs.editTree.getHalfCheckedKeys(), ...this.$refs.editTree.getCheckedKeys()].sort((a, b) => {
          return a - b
        })
      )
    },
    // 添加表单菜单选择
    handleCheckChangeEditMenu(data, checked, indeterminate) {
      this.$set(
        this.editMenuForm,
        'left_menu_ids',
        [...this.$refs.editMenuTree.getHalfCheckedKeys(), ...this.$refs.editMenuTree.getCheckedKeys()].sort((a, b) => {
          return a - b
        })
      )
    },
    // 修改状态
    changeStatus(row) {
      let msg = ''
      switch (row.status) {
        case 1:
          msg = '您确定要启用该角色吗?'
          break
        case 0:
          msg = '此操作将禁用该角色以及旗下所有角色, 是否确定?'
          break
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            await changeRoleStatus({ id: row.id, status: row.status })
          } catch (e) {
            row.status = row.status === 1 ? 0 : 1
            this.$message.error(e.message)
          }
        })
        .catch(() => {
          row.status = row.status === 1 ? 0 : 1
          this.$message.warning('您已取消操作')
        })
    },
    // 删除
    del(id) {
      this.$confirm('此操作将永久删除该角色以及旗下所有角色, 是否确定?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            await delRole({ id })
            this.search()
          } catch (e) {
            this.$message.error(e.message)
          }
        })
        .catch(() => {
          this.$message.warning('您已取消操作')
        })
    },
    // 编辑
    async edit(id) {
      try {
        const rtn = await getRoleOnly({ id })
        this.editVisible = true
        this.$nextTick(() => {
          this.editForm = rtn.info
          this.checkedKeys = rtn.info.menu_ids
          this.menuList = rtn.menuList
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 编辑角色菜单
    async editMenu(id) {
      try {
        const rtn = await getRoleMenuOnly({ id })
        this.editMenuVisible = true
        this.$nextTick(() => {
          this.editMenuForm = rtn.info
          this.checkedKeys = rtn.info.left_menu_ids
          this.menuList = rtn.menuList
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 关闭弹出前操作(不包括取消按钮)
    handleClose(formName) {
      return done => {
        this.checkedKeys = []
        this.$refs[formName].resetFields()
        // this.$refs[formName].clearValidate()
        done()
      }
    },
    // 取消按钮
    close(visibleName, formName) {
      this.checkedKeys = []
      this.$refs[formName].resetFields()
      // this.$refs[formName].clearValidate()
      this[visibleName] = false
    },
    send(visibleName, formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          switch (formName) {
            case 'editForm': // 编辑权限
              this.$set(
                this.editForm,
                'menu_ids',
                [...this.$refs.editTree.getHalfCheckedKeys(), ...this.$refs.editTree.getCheckedKeys()].sort((a, b) => {
                  return a - b
                })
              )
              try {
                await editRole(this.editForm)
                this.close(visibleName, formName)
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
            case 'editMenuForm': // 编辑角色菜单
              this.$set(
                this.editMenuForm,
                'left_menu_ids',
                [...this.$refs.editMenuTree.getHalfCheckedKeys(), ...this.$refs.editMenuTree.getCheckedKeys()].sort((a, b) => {
                  return a - b
                })
              )
              try {
                await editRoleMenu(this.editMenuForm)
                this.close(visibleName, formName)
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
            case 'addForm': // 添加权限
              try {
                await addRole(this.addForm)
                this.close(visibleName, formName)
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
          }
        } else {
          this.$message.error('请检查表单')
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped></style>
